<template>
	<view class="shop-cart">
		<view class="main " :style="{'padding-bottom':  (cartType == 1 ?  '100rpx' : 0)}">
			<view class="cart-list m-b-20" v-show="cartType==1">
				<view class="cart-item bg-white" v-if="cartMainLists&&cartMainLists.length>0">
					<view class="flex select">
						<image class="shop-icon" src="../../static/images/icon_shop.png"></image>
						<text class="shop-title">倍阅云店</text>
						<view class="icon-delivery-type">快递发货</view>
					</view>
					<view>
						<u-swipe-action :show="openCartId == item.cart_id" btn-width="150"
							v-for="item in cartMainLists[0].cart" :key="item.cart_id" :index="item.cart_id"
							@click="deleteOneCart($event, item.cart_id)" :options="options" @open="openSwipe">
							<view class="flex p-30">
								<u-checkbox :disabled="cartInvalid(item)"
									@change="changeSelect($event, 2, item.cart_id)" shape="circle" size="40"
									:value="item.selected == 1">
								</u-checkbox>
								<router-link class="flex-1"
									:to="{path: '/pages/goods_details/goods_details', query: {id: item.goods_id}}">
									<view class="flex">
										<view class="goods-img m-r-20">
											<u-image width="168rpx" height="212rpx" :src="item.image" />
											<view v-if="item.goods_status == 0 || item.goods_del == 1 || !item.stock"
												class="invalid sm white text-center">已失效
											</view>
										</view>
										<view class="info flex-1">
											<view style="font-size: 32rpx;">{{item.goods_name}}</view>
											<view class="muted line-1 xs m-t-10">
												<view v-if="item.spec_value_str.length>0"
													v-for="(cell,idx) in item.spec_value_str.split(',')" :key="idx">
													{{cell}}
												</view>
											</view>
											<view class="flex row-between m-t-20">
												<view class="price flex primary">
													<price-format :price="item.price" :first-size="32" :second-size="32"
														:subscript-size="24" :weight="500">
													</price-format>
													<price-format :color="colorConfig.muted" v-if="item.price!=item.origin_price" :first-size="26" :second-size="26" :subscript-size="24" line-through :price="item.origin_price" style="margin-left: 10rpx;"></price-format>
												</view>
												<view class="cartNum" @tap.stop="">
													<u-number-box :disabled="cartInvalid(item)" :value="item.goods_num"
														:min="1" :max="item.stock" bgColor="#fff"
														@change="countChange($event, item.cart_id)" />
												</view>
											</view>
										</view>
									</view>
								</router-link>
							</view>
						</u-swipe-action>
					</view>
				</view>

				<view class="cart-item bg-white" v-for="(items, index) in cartLists" v-if="cartLists&&items.cart.length>0" :key="index">
					<view class="flex select">
						<image class="shop-icon" src="../../static/images/icon_shop.png"></image>
						<text class="shop-title">{{items.shop.shop_name}}</text>
						<view class="icon-pick-up">自提</view>
					</view>
					<view>
						<u-swipe-action :show="openCartId == item.cart_id" btn-width="150" v-for="item in items.cart"
							:key="item.cart_id" :index="item.cart_id" @click="deleteOneCart($event, item.cart_id)"
							:options="options" @open="openSwipe">
							<view class="flex p-30">
								<u-checkbox :disabled="cartInvalid(item)"
									@change="changeSelect($event, 2, item.cart_id)" shape="circle" size="40"
									:value="item.selected == 1">
								</u-checkbox>
								<router-link class="flex-1"
									:to="{path: '/pages/goods_details/goods_details', query: {id: item.goods_id}}">
									<view class="flex">
										<view class="goods-img m-r-20">
											<u-image width="168rpx" height="212rpx" :src="item.image" />
											<view v-if="item.goods_status == 0 || item.goods_del == 1 || !item.stock"
												class="invalid sm white text-center">已失效
											</view>
										</view>
										<view class="info flex-1">
											<view style="font-size: 32rpx;">{{item.goods_name}}</view>
											<view class="muted line-1 xs m-t-10">
												<view v-if="item.spec_value_str.length>0"
													v-for="(cell,idx) in item.spec_value_str.split(',')" :key="idx">
													{{cell}}
												</view>
											</view>
											<view class="flex row-between m-t-20">
												<view class="price flex primary">
													<price-format :price="item.price" :first-size="32" :second-size="32"
														:subscript-size="24" :weight="500">
													</price-format>
												</view>
												<view class="cartNum" @tap.stop="">
													<u-number-box :disabled="cartInvalid(item)" :value="item.goods_num"
														:min="1" :max="item.stock" bgColor="#fff"
														@change="countChange($event, item.cart_id)" />
												</view>
											</view>
										</view>
									</view>
								</router-link>
							</view>
						</u-swipe-action>
					</view>
				</view>
			</view>
			<view class="cart-null flex-col col-center row-center bg-white m-b-20" style="padding: 80rpx 0 50rpx"
				v-show="cartType == 2">
				<image class="img-null" src="/static/images/cart_null.png"></image>
				<view class="muted m-b-20">购物车暂无任何商品~</view>
				<view class="primary br60 btn flex row-center" @click="goHome()">去逛逛</view>
			</view>
			<view v-if="!isLogin" class="login flex-col col-center row-center">
				<image class="img-null" src="/static/images/cart_null.png"></image>
				<view class="muted mt20">登录后才能查看购物车哦</view>
				<view class="white br60 flex row-center btn" @click="goUrl('/pages/login/login')">
					<image class="mr10" src="/static/images/icon_wechat.png"></image>
					<text>去登录</text>
				</view>
			</view>
		</view>

		<view class="footer flex bg-white" v-show="cartType == 1">
			<u-checkbox :disabled="allInvalid()" @change="changeSelect($event,3)" shape="circle" size="40"
				:value="isSelectedAll">
				<text style="font-size: 25rpx;">全选</text>
			</u-checkbox>
			<view class="primary" @tap="deleteSelectCart">删除</view>
			<view @tap="deleteInvalidCart" style="margin-left: 10rpx;color: #999;">清空失效</view>
			<view class="all-price flex lg m-r-20 row-right">
				<view style="font-size: 25rpx;">合计：</view>
				<view style="font-weight: 700;"><text style="font-size: 18rpx;">￥</text><text
						style="font-size: 28rpx;">{{totalPrice || 0}}</text></view>
			</view>
			<view class="right-btn" :style="' ' + (nullSelect ? 'background: #d7d7d7' : '')" @tap="goToConfirm">
				去结算({{totalAmount}})</view>
		</view>

		<u-modal v-model="showDelTips" :show-cancel-button="true" comfirm-text="狠心删除"
			:confirm-color="colorConfig.primary" :show-title="false" @confirm="deleteCart">
			<view class="flex-col col-center tips-dialog" style="padding-top: 40rpx">
				<image class="icon-lg" src="/static/images/icon_warning.png" />
				<view style="margin:30rpx 0;">确认删除选中商品吗？</view>
			</view>
		</u-modal>
		
		<u-modal v-model="showRemoveTips" :show-cancel-button="true" comfirm-text="移除"
			:confirm-color="colorConfig.primary" :show-title="false" @confirm="deleteCart">
			<view class="flex-col col-center tips-dialog" style="padding-top: 40rpx">
				<image class="icon-lg" src="/static/images/icon_warning.png" />
				<view style="margin:30rpx 0;">确认移除失效的商品吗？</view>
			</view>
		</u-modal>

		<u-modal v-model="showDelivery" title="请选择配送方式" :showConfirmButton="false" :maskCloseAble="true" width="616"
			:z-index="9999">
			<view class="delivery-box">
				<view class="delivery-item" :class="{'active':item.id==delivery_type}"
					v-for="(item,index) in delivery_types_arr" :key="index" @click="delivery_type=item.id">
					<image :src="item.pic"></image>
					<view style="flex: 1;display: flex;flex-direction: column;justify-content: space-between;">
						<view style="font-size: 32rpx;font-weight: 700;">{{item.name}}</view>
						<view style="font-size: 24rpx;color: #919191;">{{item.des}}</view>
					</view>
				</view>
				<view style="margin-top: 40rpx;text-align: center;">
					<view class="delivery-btn" @click="changeDeliveryType">确认</view>
				</view>
			</view>
		</u-modal>
		
		<tabbar></tabbar>
	</view>
</template>

<script>
	import {
		getCartList,
		changeCartSelect,
		changeGoodsCount,
		deleteGoods
	} from '@/api/store';
	import {
		getUser
	} from '@/api/user';
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import Cache from '@/utils/cache'
	import MescrollCompMixin from "@/components/mescroll-uni/mixins/mescroll-comp";
	export default {
		mixins: [MescrollCompMixin],
		data() {
			return {
				//购物车状态 1为有 2为空 0则什么都不显示
				cartType: 0,
				showMoreGoods: false,
				cartLists: [],
				cartMainLists: [],
				showDelTips: false,
				showRemoveTips:false,
				totalPrice: '',
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF2C3C'
					}
				}],
				openCartId: 0,
				totalAmount: '',
				showDelivery: false,
				delivery_type: '1',
				delivery_types_arr: [{
					id: '1',
					name: '快递发货',
					des: '由所购图书书店将图书通过快递发往您填写的地址',
					pic: '../../static/images/icon_delivery.png'
				}, {
					id: '3',
					name: '到店自取',
					des: '由您本人亲自来选定书店凭购书码取货',
					pic: '../../static/images/icon_pickup.png'
				}],
			};
		},

		computed: {
			...mapGetters(['cartNum', 'inviteCode']),
			// 一个都没有选中
			nullSelect() {
				const {
					cartLists,
					cartMainLists
				} = this
				let nullS = true,
					cartAllLists = cartLists.concat(cartMainLists);
				cartAllLists.forEach((item) => {
					item.cart.forEach(goods => {
						if (goods.selected) nullS = false
					})
				})
				return nullS
			},
			// 判断全选状态
			isSelectedAll() {
				const {
					cartLists,
					cartMainLists
				} = this
				if (!cartLists.length && !cartMainLists.length) return false
				if (this.allInvalid()) return false
				let index = cartLists.findIndex(item => item.is_selected == 0);
				let indexMain = cartMainLists.findIndex(item => item.is_selected == 0);
				return index == -1 ? true : false
			},

		},
		onLoad() {

		},
		onShow() {
			this.getCartListFun();
		},
		methods: {
			...mapActions(['getCartNum']),
			// 删除购物车
			deleteCart() {
				// console.log(this.cartId)
				if (!this.cartId) return this.$toast({
					title: '请选择商品'
				})
				this.showDelTips = false
				this.showRemoveTips = false
				deleteGoods({
					cart_id: this.cartId
				}).then(res => {
					if (res.code == 1) {
						this.getCartListFun();
					}
				});
			},
			openSwipe(index) {
				this.openCartId = index
			},
			cartInvalid(item) {
				return item.goods_status == 0 || item.goods_del == 1 || item.is_pay == 0 || item.has_item == 0 ? true :
					false || item.stock == 0
			},
			shopInvalid(item) {
				return item.cart.every(citem => this.cartInvalid(citem))
			},
			allInvalid() {
				return this.cartLists.every(item => this.shopInvalid(item)) && this.cartMainLists.every(item => this
					.shopInvalid(item))
			},
			// 删除选中购物车
			deleteSelectCart() {
				this.cartId = this.getSelectCart()
				this.showDelTips = !this.showDelTips;
			},
			// 删除单个购物车
			deleteOneCart(e, cartId) {
				if (cartId) {
					this.cartId = cartId;
				}
				this.showDelTips = !this.showDelTips;
			},
			// 删除失效购物车
			deleteInvalidCart(){
				this.cartId = this.getInvalidCart()
				this.showRemoveTips = !this.showRemoveTips;
			},

			async getCartListFun() {
				const {
					data: {
						lists,
						main_lists,
						total_amount,
						total_num
					},
					code
				} = await getCartList()
				if (code == 1) {
					let cartType = 0;
					if (lists.length == 0) {
						cartType = 2;
					} else {
						cartType = 1;
					}
					this.showMoreGoods = true
					this.cartLists = lists;
					this.cartMainLists = main_lists.length > 0 ? [{
						cart: main_lists,
						is_selected: 0
					}] : [];
					this.cartType = cartType;
					this.totalPrice = total_amount;
					this.totalAmount = total_num;
					this.getCartNum()
				} else {
					this.cartType = 0
				}
			},
			// 更改选中状态 type为1选中店铺/2选中商品/3全选
			changeSelect({
				value
			}, type, number) {
				let cartId = []
				const {
					cartLists,
					cartMainLists
				} = this
				let cartAllLists = cartLists.concat(cartMainLists)
				switch (type) {
					case 1:
						cartId = cartAllLists[number].cart.map(item => item.cart_id)
						break;
					case 2:
						cartId.push(number)
						break;
					case 3:
						cartId = cartAllLists.reduce((pre, item) => {
							return pre.concat(item.cart.map(i => i.cart_id))
						}, cartId)
						break;

				}
				this.changeCartSelectFun(cartId, value);
			},

			changeCartSelectFun(cartId, selected) {
				changeCartSelect({
					cart_id: cartId,
					selected: selected ? 1 : 0
				}).then(res => {
					if (res.code == 1) {
						this.getCartListFun();
					}
				});
			},
			// 数量改变
			countChange({
				value
			}, cartId) {
				console.log(value)
				let cartid = cartId;
				changeGoodsCount({
					cart_id: cartid,
					goods_num: value
				}).then(res => {
					this.getCartListFun();
				})
			},
			getSelectCart() {
				const {
					cartLists,
					cartMainLists
				} = this
				let cartAllLists = cartLists.concat(cartMainLists)
				return cartAllLists.reduce((pre, item) => {
					return pre.concat(item.cart.filter(i => i.selected && !this.cartInvalid(i)).map(i => i
						.cart_id))
				}, [])
			},
			getInvalidCart(){
				const {
					cartLists,
					cartMainLists
				} = this
				let cartAllLists = cartLists.concat(cartMainLists)
				return cartAllLists.reduce((pre, item) => {
					return pre.concat(item.cart.filter(i => i.goods_status == 0 || i.goods_del == 1 || !i.stock).map(i => i
						.cart_id))
				}, [])
			},
			goToConfirm() {
				let {
					cartLists,
					cartMainLists
				} = this;
				let goods = [];
				let carts = this.getSelectCart()
				if (carts.length == 0) return this.$toast({
					title: '您还没有选择商品哦'
				});
				// 处理出商品数组数据
				cartLists.forEach(item => {
					if (item.cart.length != 0) {
						item.cart.forEach((el, i) => {
							// 选中的商品才能进入
							if (el.selected == 1) {
								goods.push({
									item_id: el.item_id,
									num: el.goods_num,
									goods_id: el.goods_id,
									shop_id: item.shop.shop_id,
									delivery_type: 3
								})
							}
						})
					}
				})
				cartMainLists.forEach(item => {
					if (item.cart.length != 0) {
						item.cart.forEach((el, i) => {
							// 选中的商品才能进入
							if (el.selected == 1) {
								goods.push({
									item_id: el.item_id,
									num: el.goods_num,
									goods_id: el.goods_id,
									shop_id: Cache.get('SHOP_CODE'),
									delivery_type: 1
								})
							}
						})
					}
				})
				const params = {
					carts: carts,
					goods: goods,
					type: 'cart'
				};
				this.$Router.push({
					path: '/pages/confirm_order/confirm_order',
					query: {
						data: params
					}
				})
			},
			changeDeliveryType() {
				this.goToConfirm();
			},
			goUrl(url) {
				this.$Router.push({
					path: url
				})
			},
			goHome() {
				uni.switchTab({
					url: "/pages/index/index"
				});
			}
		},
	};
</script>
<style lang="scss">
	.shop-cart {
		.main {
			padding-bottom: 100rpx;
		}

		.cart-list {
			.cart-item {
				margin: 20rpx 20rpx 0;
				border-radius: 10rpx;

				.shop-icon {
					width: 35rpx;
					height: 42rpx;
				}

				.shop-title {
					margin-left: 10rpx;
					font-size: 30rpx;
				}

				.icon-delivery-type,
				.icon-pick-up {
					display: inline-block;
					height: 32rpx;
					padding: 0 10rpx;
					margin-left: 10rpx;
					border-radius: 6rpx;
					font-size: 28rpx;
					color: #fff;
					line-height: 32rpx;
				}

				.icon-delivery-type {
					background-color: #f67657;
				}

				.icon-pick-up {
					background-color: #01abe6;
				}

				.goods-img {
					position: relative;
					border-radius: 10rpx;
					overflow: hidden;

					.invalid {
						position: absolute;
						width: 100%;
						bottom: 0;
						background-color: rgba(0, 0, 0, 0.4);
					}
				}

				.info {
					max-width: 400rpx;
					min-height: 212rpx;
				}
			}

			.select {
				height: 92rpx;
				padding: 0 32rpx;
			}
		}

		.cart-null {
			.btn {
				border: 1px solid $-color-primary;
				width: 184rpx;
				margin-left: auto;
				margin-right: auto;
				padding: 8rpx 24rpx;
			}
		}

		.footer {
			position: fixed;
			padding: 0 24rpx;
			width: 100%;
			height: 150rpx;
			box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.1);
			bottom: 140rpx;
			z-index: 20;

			.all-price {
				text-align: right;
				flex: 1;
			}

			.right-btn {
				height: 62rpx;
				padding: 0 30rpx;
				background: $-color-primary;
				border-radius: 8rpx;
				font-size: 25rpx;
				line-height: 62rpx;
				color: #fff;
				text-align: center;
			}
		}

		.login {
			height: calc(100vh - var(--window-bottom) - 140rpx);
			background: #fff;
			text-align: center;

			.btn {
				background-color: #09BB07;
				width: 280rpx;
				line-height: 70rpx;
				margin: 40rpx auto 0;

				image {
					width: 50rpx;
					height: 50rpx;
				}
			}
		}
	}

	.delivery-box {
		padding: 40rpx;
		background-color: #fff;

		.delivery-item {
			display: flex;
			margin-top: 20rpx;
			padding: 30rpx;
			background-color: #f6f6f6;
			border: solid 6rpx #f6f6f6;
			border-radius: 16rpx;

			&.active {
				border: solid 6rpx #fa7b63;
			}

			image {
				width: 135rpx;
				height: 125rpx;
				margin-right: 30rpx;
				object-fit: contain;
			}
		}

		.delivery-btn {
			display: inline-block;
			width: 378rpx;
			height: 75rpx;
			background-color: $-color-primary;
			border-radius: 16rpx;
			font-size: 32rpx;
			font-weight: 700;
			line-height: 75rpx;
			color: #fff;
			letter-spacing: 10rpx;
		}
	}
</style>